
    /**  
    * @Title: Client.java
    * @Package com.utils.httpclient
    * @Description: 
    * @author likai
    * @date 2016年8月31日
    * @version V1.0  
    */
    
package com.utils.http;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
    * @ClassName: Client
    * @Description: 
    * @author likai
    * @date 2016年8月31日
    *
    */

@SuppressWarnings("deprecation")
public class ClientUtil {
	/**
     *	发送验证码
     * 
     * @param postData：请求数据，postUrl:请求链接
     *            
     * 
     * @return 所代表远程资源的响应结果
     */
	public static String SMS(String postData, String postUrl) {
        //获取响应内容体
        String line, result = "";
        try {
            //发送POST请求
            URL url = new URL(postUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setUseCaches(false);
            conn.setDoOutput(true);
 
            conn.setRequestProperty("Content-Length", "" + postData.length());
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(postData);
            out.flush();
            out.close();
 
            //获取响应状态
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                System.out.println("connect failed!");
                return "";
            }

            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
            in.close();
            return result;
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        return result;
    }
	/**
     *	URL发送请求
     * 
     * @param postData：请求数据，postUrl:请求链接
     *            
     * 
     * @return 所代表远程资源的响应结果
     */
	
	public static String UrlPostClient(String content, String urlStr) {
		URL url = null;
		HttpURLConnection connection = null;
		BufferedReader reader=null;
		StringBuffer buffer=null;
		
			try {
				url = new URL(urlStr);
				connection = (HttpURLConnection) url.openConnection();
				connection.setDoOutput(true);
				connection.setDoInput(true);
				connection.setRequestMethod("POST");
				connection.setRequestProperty("Content-Type", "application/json");
				connection.setUseCaches(false);
				connection.connect();
	
				DataOutputStream out = new DataOutputStream(connection.getOutputStream());
				out.write(content.getBytes("utf-8"));
				out.flush();
				out.close();		             				
		             // 接口调用正常
				if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				    //正常处理
					reader =new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
					buffer = new StringBuffer();
					String line = "";
					while ((line = reader.readLine()) != null) {
						buffer.append(line);
					}
					reader.close();
				}else if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
				    //错误处理
		            reader =new BufferedReader(new InputStreamReader(connection.getErrorStream(), "utf-8"));
					buffer = new StringBuffer();
					String line = "";
					while ((line = reader.readLine()) != null) {
						buffer.append(line);
					}
					reader.close();
				}
		        return buffer.toString();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (connection != null) {
					connection.disconnect();
				}
			}
		return null;

    }
	
public static void main(String[] args) {
	System.out.println(UrlPostClient("", "http://192.168.3.68:8080/pay/rest/school/apply"));
}
	
	/**
     * httpclient模拟发送http的post请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *           
     * @return 所代表远程资源的响应结果
     */
	
	@SuppressWarnings({ "resource" })
	public static String  httpClientPost(Map<String, String> param,String url) {
		try {
			
			HttpPost post=new HttpPost(url);
			post.addHeader("Content-Type","application/json; charset=UTF-8");
			post.addHeader("Accept","application/json; charset=UTF-8");
			ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();  
			List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(param.entrySet());
			for (int i = 0; i < infoIds.size(); i++) {
				Map.Entry<String, String> item = infoIds.get(i);
				if (item.getKey() != "") {					
					String key = item.getKey();
					String val = item.getValue();
					pairs.add(new BasicNameValuePair(key, val));
				}
			}
			post.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
			HttpResponse response=new DefaultHttpClient().execute(post);
			HttpEntity entity=response.getEntity();
			String returnContent=EntityUtils.toString(entity);		
			return returnContent;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return "";
	}

	/**
     * httpclient模拟发送http的get请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *           
     * @return 所代表远程资源的响应结果
     */
	
	@SuppressWarnings({ "resource" })
	public static String  httpClientGet(Map<String, String> param,String url) {
		try {
			String uri="";
			if (param!=null) {			
				List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(param.entrySet());
				for (int i = 0; i < infoIds.size(); i++) {
					Map.Entry<String, String> item = infoIds.get(i);
					if (item.getKey() != "") {					
						String key = item.getKey();
						String val = item.getValue();
						uri+=key+"="+val+"&";
					}
				}
				uri=url+"?"+uri.substring(0, uri.length()-1);
				System.out.println(uri);
				HttpGet get=new HttpGet(uri);
				get.addHeader("Accept",
						"application/json; charset=UTF-8");
				get.addHeader("Content-Type",
						"application/json; charset=UTF-8");
				HttpResponse response=new DefaultHttpClient().execute(get);
				HttpEntity entity=response.getEntity();
				String returnContent=EntityUtils.toString(entity);		
				return returnContent;
			}else {
				HttpGet get=new HttpGet(url);
				get.addHeader("Accept",
						"application/json; charset=UTF-8");
				get.addHeader("Content-Type",
						"application/json; charset=UTF-8");
				HttpResponse response=new DefaultHttpClient().execute(get);
				HttpEntity entity=response.getEntity();
				String returnContent=EntityUtils.toString(entity);		
				return returnContent;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return "";
	}
	
}
